<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/blog180x180.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/blog32x32.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/blog16x16.png?v=5.1.4">


  <link rel="mask-icon" href="/images/blog.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="linux,os,java,python," />





  <link rel="alternate" href="/atom.xml" title="袁小伙" type="application/atom+xml" />






<meta name="description" content="KVC   介绍及简单使用 有了解过C#的同学都知道，C#高级语法中有一种机制叫“反射”乍一听这名字还让人摸不着头脑，还以为是啥高科技(⊙﹏⊙)。往简单了讲，无非就只是用字符串动态去操作一个对象罢了-_-!。在C#的远房表亲OC中，也有这样功能的语法，操作起来可比C#简单的太多。这部分功能就叫KVC。    *KVC：Key  Value Coding，取其三个单词首字母浓缩而成。直白翻译过来就是">
<meta name="keywords" content="linux,os,java,python">
<meta property="og:type" content="article">
<meta property="og:title" content="第一篇博客">
<meta property="og:url" content="https:&#x2F;&#x2F;yuanxiaohuo.gitee.io&#x2F;2018&#x2F;11&#x2F;30&#x2F;hello-world3&#x2F;index.html">
<meta property="og:site_name" content="袁小伙">
<meta property="og:description" content="KVC   介绍及简单使用 有了解过C#的同学都知道，C#高级语法中有一种机制叫“反射”乍一听这名字还让人摸不着头脑，还以为是啥高科技(⊙﹏⊙)。往简单了讲，无非就只是用字符串动态去操作一个对象罢了-_-!。在C#的远房表亲OC中，也有这样功能的语法，操作起来可比C#简单的太多。这部分功能就叫KVC。    *KVC：Key  Value Coding，取其三个单词首字母浓缩而成。直白翻译过来就是">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-fd4667bdc1cc5729.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-35f76500d4a260e7.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-016e3cb7ee492b9c.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-53a1de2860bba238.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-ce7fc379da2f3776.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-c9928e025c15a53c.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-f767c866712b6221.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-728a7850a76c6437.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-78e42268ed7d93b3.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-8f935288db336c80.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-f259fa9e069ca402.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-8441ecaabffffa38.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-0d474626e2d026c1.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-c48a396c3398b330.png?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-c2899bfdb83d1e40.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-ff121557a29673d5.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-9e08e8af93b06f21.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-beafa5122a902279.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-d0e45211b9785175.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-7823d3a0dc4b8883.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-9d5397fe206f68df.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-46a38fe24928bbe0.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-13229e68374eb1d7.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-4a15f80a8867e5fd.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-83f49e7ee65bb385.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-8628aad103f3d220.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-1875be8312e09541.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-7a1083209cb8f1ea.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-b98b31c6911ffa19.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-ec7f151e9cd2d6a7.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-462f3f14320acc1b.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">
<meta property="og:updated_time" content="2019-11-26T13:07:08.835Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http:&#x2F;&#x2F;upload-images.jianshu.io&#x2F;upload_images&#x2F;2147639-fd4667bdc1cc5729.jpg?imageMogr2&#x2F;auto-orient&#x2F;strip%7CimageView2&#x2F;2&#x2F;w&#x2F;1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://yuanxiaohuo.gitee.io/2018/11/30/hello-world3/"/>





  <title>第一篇博客 | 袁小伙</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?3d0c91e04649744c19d390644f016cf0";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">袁小伙</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">专注于分享</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-about"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" target="_blank" rel="noopener" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://yuanxiaohuo.gitee.io/2018/11/30/hello-world3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yuanxiaohuo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/wangye.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="袁小伙">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">第一篇博客</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-30T17:30:00+08:00">
                2018-11-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/develop/" itemprop="url" rel="index">
                    <span itemprop="name">develop</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/develop/test/" itemprop="url" rel="index">
                    <span itemprop="name">test</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/11/30/hello-world3/" class="leancloud_visitors" data-flag-title="第一篇博客">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>KVC</strong> </p>
<ul>
<li>介绍及简单使用<ul>
<li>有了解过C#的同学都知道，C#高级语法中有一种机制叫“反射”<br>乍一听这名字还让人摸不着头脑，还以为是啥高科技(⊙﹏⊙)。往简单了讲，无非就只是用字符串动态去操作一个对象罢了-_-!。在C#的远房表亲OC中，也有这样功能的语法，操作起来可比C#简单的太多。这部分功能就叫KVC。</li>
</ul>
</li>
</ul>
<p>*<em>KVC：Key  Value Coding，取其三个单词首字母浓缩而成。直白翻译过来就是键值编码，什么意思呢？简单来说，就是操作一个对象，也可以像操作字典一样，通过key来取值和赋值。<br>*</em><br>            纳尼？真有这么神奇？接下来，我就带你走入KVC的奇妙世界<br>            我们先创建一个HMPerson类来试验一下。<br><img src="http://upload-images.jianshu.io/upload_images/2147639-fd4667bdc1cc5729.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<ul>
<li><p>注：HM为前缀，在iOS开发中用来区分是哪个框架下的类。苹果推荐所有的非苹果官方开发者都以3个字母的作为前缀，2个字母的为苹果自身保留。这里为方便起见，接下来所有创建的类，我们都以HM开头</p>
<ul>
<li><p>然后实例化HMPerson类的对象，此时，我们如果想要给它的name和age两个属性赋值和取值，就可以用点语法来操作，如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-35f76500d4a260e7.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>  但是，这种点语法方式显得着实太low，接下来我们就用比较高大上的方式——KVC的方式来赋值和取值。<br>  我们先简单看看KVC里的几个方法：</p>
</li>
</ul>
<p><strong>赋值</strong>：</p>
<ul>
<li>解释：第一个参数传入想赋的值，第二个参数传入想接收值的属性</li>
</ul>
</li>
</ul>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)setValue:(<span class="keyword">nullable</span> <span class="keyword">id</span>)value forKey:(<span class="built_in">NSString</span> *)key;</span><br><span class="line">- (<span class="keyword">void</span>)setValue:(<span class="keyword">nullable</span> <span class="keyword">id</span>)value forKeyPath:(<span class="built_in">NSString</span> *)keyPath;</span><br></pre></td></tr></table></figure>
<ul>
<li>解释：这种方式比较暴力，后头会解释<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-(<span class="keyword">void</span>)setValuesForKeysWithDictionary:(<span class="built_in">NSDictionary</span>&lt;<span class="built_in">NSString</span> *, <span class="keyword">id</span>&gt;*)keyedValues;</span><br></pre></td></tr></table></figure>


</li>
</ul>
<p><strong>取值：</strong></p>
<figure class="highlight erlang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- <span class="params">(nullableid)</span>valueForKey:<span class="params">(NSString *)</span>key;</span><br><span class="line">- <span class="params">(nullable id)</span>valueForKeyPath:<span class="params">(NSString *)</span>keyPath;</span><br></pre></td></tr></table></figure>
<ul>
<li>解释：参数是传入你想取值的属性名  我们都知道，OC中任何对象都直接或间接的继承自NSObject，而在Foundation框架中，NSObject有个叫“NSKeyValueCoding”的分类，里面就包含了上面所有这些KVC方法。因此任何对象都可以通过KVC来取值和赋值，也就是说即使我们刚刚自己创建的Person类也有这些方法。 取值和赋值具体在代码中的应用如下：</li>
</ul>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-016e3cb7ee492b9c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<ul>
<li>我们发现KVC的方式使用起来也没任何问题。但是，很多同学会疑惑，为什么<br>16要加个“@”符号呢？还有取值时为什么还要调用一下intValue方法呢？不这么写可不可以？答案是不行的，我们先看如果不这么写会怎样</li>
</ul>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-53a1de2860bba238.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="143731y7z0i0l67wzeuzcm.png.thumb.jpg"></p>
<ul>
<li>此时发现，如果不按之前的写法会有一个错误以及一个警告。原因如下   <ol>
<li>KVC中，赋值时传入的值都只能是对象类型，无法直接传入基本数据类型，因此，在给age属性赋值时，用了一个@符号，把16这个数字快速包装成了NSNumber类型（@加数字是快速创建NSNumber的语法）   </li>
<li>通过KVC取值时，所有的返回值类型都是id类型（也即对象类型），因此无法直接用基本数据类型的变量来接收，必须调用其对应的类型转换代码先进行类型转换另外需要注意：KVC中所有的属性名都要以字符串的形式传入此时有同学会疑问了：“我勒个去！用<br>KVC这么麻烦，还不如直接用点语法方便多了”，对，一般情况下是这样！但是，用<br>KVC的方式有你意想不到优点！</li>
</ol>
</li>
</ul>
<hr>
<p><strong>KVC<br>**</strong>的优点合集</p>
<p>**<br><strong>优点一：破门而入：与别人家的“私人专属”亲密接触</strong><br>我们都知道，如果@property写在.h文件中，代表外界可以通过调用对应的setter和getter方法（或点语法）来访问对应的私有成员变量，但如果写在.m中，代表只允许本类中访问，其他地方访问不了。因此，我们给之前的Person类在.m文件中写一个延展，<a href="mailto:%E6%8A%8A.h%E6%96%87%E4%BB%B6%E7%9A%84@property%E6%8C%AA%E5%88%B0.m" target="_blank" rel="noopener">把.h文件的@property挪到.m</a>的延展中。并且在.m文件中再加一个用@private修饰的成员变量<br>如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-ce7fc379da2f3776.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>此时，我们通过点语法来给属性赋值取值即会报错，如图<br><img src="http://upload-images.jianshu.io/upload_images/2147639-c9928e025c15a53c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>但是，如果是KVC方式，此时依然坚挺！<br><img src="http://upload-images.jianshu.io/upload_images/2147639-f767c866712b6221.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>到此为止，KVC的好处之一得到完美体现：无论类中的成员是否私有，用KVC都可以强行“破门而入”，对它们正常取值和赋值。<br>除此以外，还有个显而易见的好处是：KVC中不管你的成员变量是否加下划线，你用KVC取值和赋值时传入的属性名都可以不带下划线。<br>*<em>优点二：大大简化字典转模型代码<br>*</em><br>     很多时候，我们通过加载本地文件，或者网络请求会得到一个数据字典，为了方便调用，一般我们都会将这个字典转换为对应的模型类，但是，不用KVC的转换方法太过费劲，如图：<br>先有一个HMPerson类<br><img src="http://upload-images.jianshu.io/upload_images/2147639-728a7850a76c6437.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>然后有一个字典，并且把字典里的元素赋值给HMPerson对象，如下图所示：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-78e42268ed7d93b3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>此时用点语法相当的麻烦，如果有100个属性，就必须一个元素一个元素地写100次。但用KVC的方式如何呢？我们看代码：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-8f935288db336c80.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>有同学看到这可能会疑惑了，KVC方式也没见得有多简便啊，代码看起来更多了！对，目前来说是这样子，但是大家仔细观察，setValue和ForKey两个参数里传入的key名是不是完全一样？如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-f259fa9e069ca402.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>而这些Key，是不是刚好可以在遍历这个字典数据就可以获取到？如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-8441ecaabffffa38.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<pre><code>大家看，在这个循环里，key好像就是我们用KVC的setValue:值 forKey:键 中需要传入的“键”，而dic[key]就是正方法中需要传入的“值”。</code></pre><p>因此，我们可以将KVC实现字典转模型的方法直接用这个循环解决，如图：<br>     <img src="http://upload-images.jianshu.io/upload_images/2147639-0d474626e2d026c1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<pre><code>看，此时是不是特别方便，代码特别简洁？哪怕以后字典有100项数据，对应实体类100个属性，再不用怕，就用这一个循环即可搞定！
                   但，这还不够简洁！</code></pre><p>KVC提供了一套更简洁的操作方式，只需你传入一个字典，就可以帮你自动把字典里的每一项赋值给你实体类对应的属性，如图：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-c48a396c3398b330.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="14.png"></p>
<p>对，仅需调用setValuesForKeysWithDictionary方法，传入字典即可。这个方法内部，帮我们做了我们刚刚循环字典的操作，因此仅仅这一个方法就可完成字典数据转模型数据，从此，妈妈再也不用担心我写多余代码了！<br>注意：用setValuesForKeysWithDictionary或者自己写循环做字典数据转模型数据时，必须保证实体类的属性跟字典中的key名字一一对应，并且属性可以比字典多，但是绝对不能比字典的元素少！</p>
<hr>
<p><strong>KVC<br>**</strong>疑问解密</p>
<p>**<br>**       疑问解密<br>1：<br>**</p>
<p>使用KVC是直接对成员变量赋值，还是调用了这个成员变量对应的setter和getter方法呢？<br>为了解决这个疑问，我们给HMPerson类里加一个私有的成员变量name，并且给它写好对应的getter和setter方法，如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-c2899bfdb83d1e40.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>然后用KVC的方式给name赋值和取值，如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-ff121557a29673d5.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>通过观察，我们发现用KVC来赋值时，对应的setter方法能被调用，用KVC来取值时，对应的getter方法也能被调用。<br>因此小伙伴们不用担心KVC会破坏自己已经写好的属性封装规则。<br><strong>疑问解密1小分支：</strong></p>
<p>如果没有getter方法和setter方法时，KVC是怎么找成员变量的呢？<br>为了弄清这个问题，我们删掉name的getter和setter方法。如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-9e08e8af93b06f21.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>然后通过KVC方式赋值取值，会发现，依然可以赋值和取值成功。并且是给p对象的成员变量_name赋值的。如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-beafa5122a902279.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-d0e45211b9785175.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>小伙伴们可能好奇的是，传入的Key是“name”，而赋值成功的是“_name”成员变量，那么如果，我同时有两个成员变量，一个叫“_name”，一个叫“name”，那KVC是给谁赋值的呢？<br>为了搞清这个问题，我们先改良一下HMPerson类。<br><img src="http://upload-images.jianshu.io/upload_images/2147639-7823d3a0dc4b8883.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>然后，我们再次用KVC来调用，并且下一个断点看看，究竟是给哪个成员变量赋值的。如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-9d5397fe206f68df.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>通过结果，我们发现，依然是对“_name”这个成员变量赋值的。这时候我们是否可以说，KVC永远是对带下划线的成员变量赋值的呢？那倒也未必，我们来继续看，假如此时给HMPerson删掉“_name”，只留“name”，又会是怎样。<br>如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-46a38fe24928bbe0.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-13229e68374eb1d7.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>此时发现，用KVC赋值的就是这个不带下划线的成员变量（即name）了。<br>因此，我们可以总结出，KVC赋值和取值的一套顺序：</p>
<ol>
<li>用KVC取值或赋值时，会优先找这个属性对应的getter或setter方法来对这个属性赋值</li>
<li>如果找不到，则会查找带下划线的属性，如果找到则赋值</li>
<li>如果依然找不到，则会查找不带下划线的属性，如果找到则赋值</li>
<li>如果还是找不到，则报错（可以让它不报错，后文会详述）</li>
</ol>
<p>**疑问解密2：复合路径</p>
<p>**<br>  setValue:属性值 forKeyPath:属性路径 valueForKeyPath:属性名</p>
<p><em>复制代码</em></p>
<p>后面带Path的跟之前我们用的KVC有什么不同呢？我们来研究研究！<br>假设此时有一个Dog类，而Person类里也有个属性是Dog类型的，叫pet，如图<br><img src="http://upload-images.jianshu.io/upload_images/2147639-4a15f80a8867e5fd.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-83f49e7ee65bb385.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>如果此时实例化Person对象，要用KVC操作pet属性里的nickName属性就不太方便，只能先取出pet属性指向的Dog对象，再来操作nickName属性，如下：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-8628aad103f3d220.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>而带Path的方法，就是用来简化这种操作的，我们看<br><img src="http://upload-images.jianshu.io/upload_images/2147639-1875be8312e09541.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>因此，也就是说，如果需要操作访问一些“属性里的属性”时，就用带Path的方法来操作。<br>**       疑问解密<br>3：</p>
<p>**<br>            如果用<br>KVC赋值时，某一个<br>Key，类中没有会怎样？</p>
<p>例如：我们的<br>HMPerson类现在没有<br>salary属性。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-7a1083209cb8f1ea.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>此时，通过<br>KVC的方式赋值，运行时会崩溃</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-b98b31c6911ffa19.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>因此，用KVC时传入的Key必须保证类中存在同名的属性。否则会运行时崩溃。那么如果我不希望运行时直接崩溃，而是来一个相对友好的提示，不要让它崩溃，该怎么办呢？<br>我们就需要在HMPerson类里重写setValue:值   forUndefinedKey:键方法，这样，当用KVC对Person对象赋值了一个Key与属性对应不上的错误时，系统会自动调用这个方法，我们来试试看！<br>如图：<br><img src="http://upload-images.jianshu.io/upload_images/2147639-ec7f151e9cd2d6a7.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p><img src="http://upload-images.jianshu.io/upload_images/2147639-462f3f14320acc1b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>此时，无论你输错多少次HMPerson对象不存在的属性时，都不会在运行时让程序崩溃，达到报错“友好”的目的。<br>**总结</p>
<p>**<br>            KVC是一套方便我们用字符串来操作对象的机制，可以使得操作对象时跟操作字典一样的灵活。在字典转模型的领域中应用起来极为方便，并且<br>KVC可以轻松的帮我们突破访问限制的一些问题，直接访问到私有成员。</p>
<pre><code>但是同样，</code></pre><p>KVC也有其缺点：例如在编码时很容易输错<br>key导致问题，语法相较点语法而言也略微繁琐。但万事万物不也正如<br>KVC一般既有其优点，也存在其不足之处，不是吗？</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="yuanxiaohuo 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="yuanxiaohuo 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/linux/" rel="tag"># linux</a>
          
            <a href="/tags/os/" rel="tag"># os</a>
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/python/" rel="tag"># python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/30/hello-world1/" rel="prev" title="第二篇博客">
                第二篇博客 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/wangye.png"
                alt="yuanxiaohuo" />
            
              <p class="site-author-name" itemprop="name">yuanxiaohuo</p>
              <p class="site-description motion-element" itemprop="description">学习永远不晚</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/792477252" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/b590ae809d13" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; Wed Nov 20 2019 08:00:00 GMT+0800 (GMT+08:00) &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yuanxiaohuo</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count"></span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a></div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  





  
  







  
  
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/canvas_lines.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("h18ANRmWEp1cmsAEJ3kNQwuC-gzGzoHsz", "dhG37CuE9s2HAvUKqDnwEE2j");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
